import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 在发送请求之前做些什么
    // 从localStorage获取token（需要先在登录成功后存储）
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error: any) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据做点什么
    const { data } = response;
    
    // 根据后端返回的数据结构进行调整
    if (data.code === 200 || data.success) {
      return data;
    } else {
      // 处理业务错误
      return Promise.reject(new Error(data.message || '请求失败'));
    }
  },
  (error: any) => {
    // 对响应错误做点什么
    const { status } = error.response || {};
    
    switch (status) {
      case 401:
        // 未授权，跳转到登录页
        localStorage.removeItem('token');
        window.location.href = '/login';
        break;
      case 403:
        // 权限不足
        console.error('权限不足');
        break;
      case 404:
        // 资源不存在
        console.error('请求的资源不存在');
        break;
      case 500:
        // 服务器错误
        console.error('服务器内部错误');
        break;
      default:
        console.error('网络错误');
    }
    
    return Promise.reject(error);
  }
);

// 导出常用的请求方法
export const get = <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> => {
  return service.get(url, config);
};

export const post = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return service.post(url, data, config);
};

export const put = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return service.put(url, data, config);
};

export const del = <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> => {
  return service.delete(url, config);
};

export const patch = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return service.patch(url, data, config);
};

// 导出axios实例
export default service;